// index.js
import {
  getRecordsById,
  getUserInfoById,
  getTaskList,
  getTaskCount,
  addTasks,
  setTaskComplete,
  editPatient,
  setPayAttention
} from '../../api/index'
import {
  taskCountType,
  taskType,
  findTypeByLabel,
  userType,
  findTypeByValue,
  frequencyType,
  payType,
  illnessType,
  pathologicalStagingType
} from '../../utils/type';
import {
  formatTimeTask
} from '../../utils/util'

const app = getApp()
Page({
  data: {
    active: 0,
    logined: true,
    baseCls: 'page_account',
    avatar_icon: '/assets/images/avatar.png',
    tab_active: 1,
    activeName: 1,
    followChecked: false,
    radio: [],
    disabled: true,
    patientTaskKey: '今日任务',
    show: false,
    task_type: [{
        code: '1',
        name: '冥想'
      },
      {
        code: '2',
        name: '用药提醒'
      },
      {
        code: '3',
        name: '复查复诊'
      }
    ],
    sms_checked: false,
    repeat_checked: false,
    addshow: false,
    infoshow: false,
    filter: {
      countType: undefined
    },
    taskCount: {
      onGoing: 0,
      Finish: 0,
      Delay: 0
    },
    taskType,
    frequencyType,
    AllPatientRecords: []
  },

  onShow: function () {
    let userInfo = wx.getStorageSync('userInfo');
    this.getPatientInfo();
    if (userInfo) {
      this.setData({
        logined: true,
        show: false,
        userInfo: userInfo,
        patientTaskKey: '今日任务'
      })
      setTimeout(() => {
        this.TaskList();
        this.reset();
      }, 200)
    } else {
      this.setData({
        logined: false,
        show: true
      })
    }
  },

  onLoad(options) {
    this.setData({
      id: options.id
    })
  },
  onChange(event) {
    const detail = event.detail
    if (detail.title === '病程记录') {
      this.PatientRecords()
    }
  },
  collapse_onChange(event) {
    this.setData({
      activeName: event.detail,
    });
  },
  radio_onChange(event) {
    this.setData({
      radio: event.detail,
    });
  },


  /*
   * 备注信息获取
   * */
  RemarkonChange(e) {
    this.setData({
      disabled: false
    })
    this.setData({
      Remark: e.detail
    })
  },
  /**
   * 更新备注
   * */
  updateRemark() {
    this.setData({
      disabled: true
    })
    editPatient({
      id: this.data.patientInfo.id,
      remark: this.data.Remark
    }).then(res => {
      this.getPatientInfo();
      wx.showToast({
        title: '更新成功',
        icon: 'none',
        duration: 2000
      })
    })
  },

  /**
   * 重点关注
   */
  switch_onChange({
    detail
  }) {
    setPayAttention({
      id: this.data.patientInfo.id,
      isFollow: detail ? 1 : 0
    }).then(res => {
      this.setData({
        followChecked: detail
      })
    })
  },
  /*
   * 获取患者个人信息
   * */
  getPatientInfo() {
    let that = this;
    let id = that.data.id
    getUserInfoById(id).then(res => {
      const data = res.data;
      data.payType = findTypeByValue(data.payType, payType)?.label || '-'
      data.huiminbao = (+data.huiminbao === 0) ? '否' : '是'
      data.pathologicalStaging = findTypeByValue(data.pathologicalStaging, pathologicalStagingType)?.label || '-'
      data.diagnosis = findTypeByValue(data.diagnosis, illnessType)?.label || '-'
      if (data.medicationTime) {
        let date = new Date(data.medicationTime.replaceAll('-', '/'));
        data.medicationTime = `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`
        console.log('---debug time---', date.getFullYear(), date.getMonth(), date.getDate());

      }
      this.setData({
        patientInfo: data,
        followChecked: !!res.data.isFollow
      })
    })
  },
  /*
   * 病程记录
   */
  PatientRecords(e) {
    let that = this;
    setTimeout(() => {
      let id = that.data.patientInfo?.id;
      getRecordsById(id).then(res => {
        const records = res.rows

        for (let i = 0; i < records.length; i++) {
          let datetime = new Date(records[i].createTime.replaceAll('-', '/'));
          let date = `${datetime.getFullYear()}/${datetime.getMonth() + 1}/${datetime.getDate()}`
          records[i].date = date
        }

        let DateRecords = records
        if (typeof (e) !== 'undefined') {
          DateRecords = records.filter(item => item.date == e);
        }

        let dyRecords = {}
        DateRecords.forEach(item => {
          if (!dyRecords[item.date]) {
            dyRecords[item.date] = []
          }

          if (dyRecords[item.date]) {
            dyRecords[item.date].push(item)
          }
        })

        let dyArray = []
        for (const key in dyRecords) {
          if (dyRecords.hasOwnProperty.call(dyRecords, key)) {
            const element = dyRecords[key];
            dyArray.push({
              date: key,
              list: element[0] // 设计上只有1个
            })
          }
        }

        that.setData({
          PatientRecords: dyArray
        })
      })
    }, 100)
  },
  /**
   * 日期筛选病程记录
   * */
  getPatientRecords(e) {
    let datetime = new Date(e.detail.value)
    let date = `${datetime.getFullYear()}/${datetime.getMonth() + 1}/${datetime.getDate()}`
    this.PatientRecords(date);
  },
  /**
   * 重置日期
   * */
  reset(e) {
    var recordDate = this.selectComponent('#recordDate');
    recordDate.setData({
      value: ''
    })
    this.PatientRecords();
  },

  /**
   * 任务key
   */
  TaskList(e) {
    if (typeof (e) !== 'undefined') {
      var key = e.currentTarget.dataset.key;
    } else {
      var key = this.data.patientTaskKey;
    }
    const countType = findTypeByLabel(key, taskCountType)
    const taskListKey = `allTaskList.${countType.key}`
    const params = {
      pageNum: 1,
      pageSize: 999,
      classify: 'receive',
      type: countType?.value,
      userId: this.data.patientInfo.id
    }
    this.setData({
      patientTaskKey: key
    })
    getTaskList(params).then(res => {
      const rows = res.rows;
      const unfinishRows = [];
      const finishRows = [];
      rows.forEach(item => {
        if (item.isComplete) {
          finishRows.push(item)
        } else {
          unfinishRows.push(item)
        }
      })

      const data = {
        filter: {
          countType
        },
      }
      data[taskListKey] = {
        rows: [...unfinishRows, ...finishRows],
        finishIds: finishRows.map(item => item.id) || [],
        finishRows: finishRows,
        unfinishRows: unfinishRows
      }
      this.setData(data)

      setTimeout(() => {
        this.setData(data)
      }, 200)
    })

    this.taskCount()
  },
  /*
   * 任务数据统计
   * onGoing 待完成 / Finish 已完成 / delay 已延期
   */
  taskCount() {
    let that = this;

    getTaskCount({
      userId: this.data.patientInfo.id
    }).then(res => {
      const data = res.data;
      that.setData({
        taskCount: {
          onGoing: data.progress,
          Delay: data.delay,
          Finish: data.complete
        },
        receiveCount: data.receive,
        sendCount: data.send
      })
    })
  },

  /**
   *  任务详情
   * */
  getTaskInfo(e) {
    var that = this;
    var id = e.currentTarget.dataset.id;
    let taskList = this.data.allTaskList[this.data.filter.countType.key]
    let currTask = taskList.rows.filter(item => item.id === id)
    if (currTask.length > 0) {
      currTask = currTask[0]
    }
    let userLabel = findTypeByValue(currTask.executorUserType, userType)?.label || '-'
    let executor = `${userLabel}：${currTask.executorUserName}`
    let frequency = findTypeByValue(currTask.frequency, frequencyType)?.label || '-'

    that.setData({
      infoshow: true,
      TaskInfo: {
        ...currTask,
        executor,
        frequency
      }
    })

    wx.setPageStyle({
      style: {
        overflow: 'hidden'
      }
    })
  },

  hideshow() {
    this.setData({
      show: false,
      addshow: false,
      infoshow: false,
      repeat_checked: false,
      sms_checked: false
    })
    wx.setPageStyle({
      style: {
        overflow: 'auto'
      }
    })
  },

  /**
   * add show 
   * */
  addTaskShow() {
    this.setData({
      TaskForm: {},
      addshow: true,
      disabled: false
    })
    wx.setPageStyle({
      style: {
        overflow: 'hidden'
      }
    })
  },

  /**
   * 新增任务
   * */
  addTaskSubmit() {
    let fields = this.data.TaskForm
    const data = { ...fields }
    data.isRepeat = data.isRepeat ? 1: 0
    data.senderId = this.data.userInfo.id
    data.executorId = this.data.patientInfo.id
    data.isMsg = data.isMsg ? 1: 0
    data.type = findTypeByLabel(data.type, taskType).value

    if (data.isRepeat) {
      delete data.taskDate
      data.frequency = findTypeByLabel(data.frequency, frequencyType).value
    } else {
      delete data.beginDate
      delete data.endDate
    }

    addTasks(data).then(res => {
      wx.showToast({
        title: '新增成功',
        icon: 'none',
        duration: 2000
      })
      this.hideshow()
      this.taskCount()
      this.TaskList();
      this.reset();
      this.setData({
        TaskForm: ''
      })
    })
  },

  /**
   *  编辑任务弹窗弹出
   * */
  editTaskShow(e) {
    var that = this;
    var id = e.currentTarget.dataset.id;
    let taskList = this.data.allTaskList[this.data.filter.classify.key][this.data.filter.countType.key]
    let currTask = taskList.rows.filter(item => item.id === id)
    if (currTask.length > 0) {
      currTask = currTask[0]
    }
    let editTask = {
      ...currTask
    }
    editTask.type = findTypeByValue(editTask.type, taskType)?.label || taskType[0].label
    editTask.frequency = findTypeByValue(editTask.frequency, frequencyType)?.label || frequencyType[0].label

    // 筛选执行者
    const patients = this.data.MyPatient.filter(item => item.id === editTask.executorId)
    if (patients.length > 0) {
      editTask.teacherUserName = patients[0].teacherName
      editTask.teacherId = patients[0].teacherId
    }

    that.setData({
      editshow: true,
      TaskForm: editTask
    })

    wx.setPageStyle({
      style: {
        overflow: 'hidden'
      }
    })
  },
  /**
   * 编辑任务提交
   * */
  editTaskSubmit() {
    let that = this;
    that.setData({
      editdisabled: true
    })
    let fields = this.data.TaskForm
    if (JSON.stringify(fields) === {} || typeof fields === 'undefined') {
      wx.showToast({
        title: '任务没有修改，无法提交',
        icon: 'none',
        duration: 2000
      })
      that.setData({
        editdisabled: false,
      })
      return;
    }

    const data = { ...fields }
    data.senderId = this.data.userInfo.id
    data.frequency = findTypeByLabel(data.frequency, frequencyType).value
    data.type = findTypeByLabel(data.type, taskType).value
    data.isRepeat = data.isRepeat ? 1: 0
    data.isMsg = data.isMsg ? 1: 0

    if (data.isRepeat) {
      delete data.taskDate
    } else {
      delete data.beginDate
      delete data.endDate
    }

    editTasks(data).then(res => {
      that.setData({
        editdisabled: false,
        TaskForm: ''
      })
      wx.showToast({
        title: '更新成功',
        icon: 'none',
        duration: 2000
      })
      this.hideshow()
      this.taskCount()
      this.TaskList();
      this.reset();
    })

  },

  /* 任务类型 */
  setTaskType(e) {
    this.setData({
      'TaskForm.type': findTypeByValue(e.detail.value.value, taskType)?.label || taskType[0].label
    })
  },

  /* 任务日期 */
  setTaskDate(e) {
    this.setData({
      'TaskForm.taskDate': formatTimeTask(e.detail.value)
    })
  },

  /* 重复 */
  repeat_checked(e) {
    this.setData({
      'TaskForm.isRepeat': e.detail
    })
  },

  /* 任务时间 */
  setTaskTime(e) {
    this.setData({
      'TaskForm.taskTime': e.detail.value
    })
  },

  /*开始日期 */
  setStartTime(e) {
    this.setData({
      'TaskForm.beginDate': formatTimeTask(e.detail.value)
    })
  },

  /*结束日期 */
  setEndTime(e) {
    this.setData({
      'TaskForm.endDate': formatTimeTask(e.detail.value)
    })
  },

  /* 内容 */
  setContent(e) {
    this.setData({
      'TaskForm.content': e.detail
    })
  },

  /* 短信提醒 */
  setSMS(e) {
    console.log(e.detail)
    this.setData({
      'TaskForm.isMsg': e.detail
    })
  },
  /* 频次 */
  setFrequency(e) {
    this.setData({
      'TaskForm.frequency': findTypeByValue(+e.detail.value.value, frequencyType)?.label
    })
  },

})